import React, { Component } from 'react';
import { connect } from 'dva';
import { Toast, Icon, InputItem, List, Button, Modal, WingBlank, Picker } from 'antd-mobile';
import { getSealImages } from 'components/ImpressionLibrary/seal-config-render'
import style from './index.less';
import { sealConfigs, ENTER_TYPE } from 'utils/Enum';
import MyNavBar from 'components/navbar';
import { createForm } from 'rc-form';
import { checkUrl } from 'utils/utils'
import router from 'umi/router';
import { getIsDingTalk, backToOut } from 'utils/utils';
import { staffName } from 'utils/regular'
import commonStyles from 'utils/common.less';
import styles from '../PersonalCertificationDetail/index.less';
import { recordEnterHistoryNum } from '../../utils/utils';

const alert = Modal.alert;
/*
 * @Author: 刘琪
 * @Date: 2019-12-16 10:02:54
 * @LastEditTime : 2020-01-05 11:10
 * @LastEditors  : Please set LastEditors
 * @Description: 印章自动生成
 * @FilePath: \Electronic_Seal_Mobile\src\pages\ImpressionLibrary\index.js
 */


@connect(({ ImpressionLibraryModel, upImgModel, pdfModel }) => ({ ImpressionLibraryModel, upImgModel, pdfModel }))
class sealDetail extends Component {
	constructor(props) {
		super(props)
		this.state = {
			sealConfigData: [],
			sealForm: [],
			staffSize: '',
			configType: '',
			backUrl: '/Signature',
			errorStaffName: false,
			staffIndex: 0,
			paramType: 'code',
			name: '',
			code: '',
			lineText: '',
			topLineText: '', 
			enterpriseEnglishName: '',
			bottomLineText: '',
			text1: '',
			text2: '',
			text3: '',
			text4: '',
		}
	}
	componentDidMount() {
		const {
			location: { query },
		} = this.props;
		if (!checkUrl(query)) {
			alert('警告', '无法操作！', [
				{ text: '返回', onPress: () => backToOut() },
			])
			return
		}
		sealConfigs.forEach((item, i) => {
			if (i === 0) {
				item.check = 0
				const { height, width } = item.config[item.check]({ name: '', code: '' })
				this.setState({
					staffSize: height + 'x' + width,
					configType: item.config[item.check],
				})
			} else {
				item.check = -1
			}

		})

		this.getStaffConfig(sealConfigs)
		this.getEnterpriseName()
		const isEnterPage = localStorage.getItem('isEnterPage') || 'yes';
		if (isEnterPage === 'yes') {
			recordEnterHistoryNum();
		}
		const { location: { query: { unifiedSocialCreditCode = '' } } } = this.props
		this.setState({
			code: unifiedSocialCreditCode
		})
	}

	getEnterpriseName = () => {
		const Session = localStorage.getItem('Session');
		Toast.loading('加载中...', 0)
		let { dispatch } = this.props
		//去查询用户的wsid
		dispatch({
			type: 'ImpressionLibraryModel/getUserWsid',
			payload: Session,
			callback: (state, wsid) => {
				if (state === 'error') {
					Toast.fail('未登录', 2, () => {
						// backToOut();
					})
				} else {
					dispatch({
						type: 'pdfModel/getEnterpriseUsers',
						payload: { userWsid: wsid },
						callback: () => {
							const { pdfModel: { enterpriseObj: { enterpriseAccountAuthentication: { enterprise: { name } } } } } = this.props
							this.setState({ name })
							Toast.hide();
						}
					})
				}

			}
		})

	}

	getStaffConfig = (sealConfigs) => {
		const sealConfigData = []
		const sealForm = []
		sealConfigs.forEach((item) => {
			const sealObj = {
				name: item.name,
				base: item.config.map(item => getSealImages(item({}))),
				config: item.config,
				check: item.check,
				size: item.size
			}
			sealForm.push({ form: item.type })
			sealConfigData.push(sealObj)
		})
		this.setState({
			sealConfigData,
			sealForm
		})
	}

	checkImg = (index, config, check) => {
		const { sealConfigData } = this.state
		//如果当前点击的是当前选择的就不修改
		if (check !== -1) return
		const data = config[0]({})
		const { height, width } = data
		sealConfigData.forEach((item) => {
			item.check = -1
		})
		sealConfigData[index].check = 0
		this.setState({
			sealConfigData,
			staffSize: height + 'x' + width,
			configType: config[0],
			staffIndex: index
		})
	}

	getInputNameValue = (e) => {
		this.setState({
			name: e
		})
	}
	makeStaff = (e) => {
		const { paramType } = this.state
		this.setState({
			[paramType]: e
		})
	}
	saveParams = (e) => {
		this.setState({
			paramType: e
		})
	}

	makeSure = () => {
		const { form: { validateFields } } = this.props;
		const { code, name, configType, staffSize, lineText, topLineText, enterpriseEnglishName, bottomLineText, text1, text2, text3, text4 } = this.state
		const configData = { name, codeNum: code, EnglishName: enterpriseEnglishName, text: lineText, topText: topLineText, bottomText: bottomLineText, bank: text1, account: text2, tel: text3, adress: text4 }

		const [width, height] = staffSize.split('x')
		validateFields((error, values) => {
			if (!error) {
				const url = getSealImages(configType(configData))
				const { dispatch } = this.props
				dispatch({
					type: 'upImgModel/upImg',
					payload: {
						from: 'DEFAULT',
						name: values.staffName,
						base64: url.replace(/^data:image\/\w+;base64,/, ""),
						dimension: JSON.stringify({
							width: width,
							height: height
						}),
					},
					callback: (state, msg) => {
						if (state === 'success') {
							Toast.success(msg, 2, null, false)
							const { location: { query: { popType } } } = this.props;
							let enterType = localStorage.getItem('enterType')
							if (enterType == ENTER_TYPE.EXTERNAL) {
								// backToOut();
								window.location.href = localStorage.getItem('returnUrl')
							} else {
								router.push({ pathname: '/Signature', params: { type: popType } })
							}
						} else {
							Toast.fail(msg, 2, null, false)
						}
					}
				})
			} else {
				Toast.fail("请将必填项填写完整！")
			}
		});
	}

	getInputValue = (e) => {
		if (!staffName.reg.test(e)) {
			this.setState({
				errorStaffName: true
			})
		} else {
			this.setState({
				errorStaffName: false,
			})
		}
	}

	getForm = () => {
		const { getFieldDecorator } = this.props.form;
		const { sealForm, staffIndex } = this.state
		const { location: { query: { unifiedSocialCreditCode = '' } } } = this.props
		let dom = ''
		if (sealForm.length > 0) {
			const formArr = sealForm[staffIndex]
			if (formArr.form.length > 0) {
				dom = formArr.form.map((item, index) => {
					return (
						<div key={index}>
							{getFieldDecorator(item.key, {
								initialValue: item.key === 'code' ? unifiedSocialCreditCode : '',
								rules: [
									{
										required: false,
										message: '',
									},
								],
							})(
								<InputItem clear placeholder={"请输入" + item.title} onFocus={this.saveParams.bind(this, item.key)} onChange={this.makeStaff}>
									<span style={{ color: 'red', marginLeft: '7px' }}>{/** * */}</span>{item.title}
								</InputItem>
							)}
						</div>)
				})
			}
		}
		return dom
	}


	changePicker = val => {
		val = val[0]
		const { sealConfigData } = this.state
		let a = sealConfigData.slice()
		a.forEach(item => {
			if (item.check !== -1) {
				item.check = item.size.map(item => item.value).indexOf(val)
			}
		})
		this.setState({
			sealConfigData: a,
			staffSize: val
		})
	}

	render() {
		const { sealConfigData, staffSize, configType, name, code, lineText, topLineText, enterpriseEnglishName, bottomLineText, text1, text2, text3, text4, errorStaffName } = this.state
		const { getFieldDecorator } = this.props.form;
		const configData = { name, codeNum: code, EnglishName: enterpriseEnglishName, text: lineText, topText: topLineText, bottomText: bottomLineText, bank: text1, account: text2, tel: text3, adress: text4 }
		let enterType = localStorage.getItem('enterType')
		let url = ''
		url = enterType == ENTER_TYPE.EXTERNAL ? '' : '/Signature'
		let status = false
		if (enterType == ENTER_TYPE.EXTERNAL) {
			status = true
		}
		const isDingTalk = localStorage.getItem('isDingTalk')
		// const contentContainer=style.sealCreate+' '+commonStyles.headerTop
		const contentContainer = isDingTalk === 'true' ? style.sealCreate : style.sealCreate + ' ' + commonStyles.headerTop
		let picker = sealConfigData.filter(item => item.check !== -1)
		picker = picker.length > 0 ? picker[0].size : []
		// console.log(staffSize, picker)
		return (
			<div className={style.pageContainer} >
				<MyNavBar title={"印模库"} backUrl={url} isExternal={status} />
				<div style={{ overflow: 'auto', height: '15rem' }}>
					<div className={contentContainer}>
						<div className={style.sealStyle}>
							<div className={style.Title}>
								<span>选择印章样式</span>
							</div>
							<div className={style.sealTemplateImg}>
								<List className={style.sealTemplateImgList}>
									<div className={style.imgArr}>
										{sealConfigData.map((item, index) => (
											<div className={style.staffItem} key={index}  >
												<div className={style.imgItem} >
													<img src={item.base[item.check === -1 ? 0 : item.check]} onClick={this.checkImg.bind(this, index, item.config, item.check)} style={{ border: item.check !== -1 ? '1px dashed rgba(0,137,255,1)' : '' }} />
													{item.check !== -1 ? <Icon type='check-circle' className={style.check} color='#0089FF' /> : ''}
												</div>
												<div className={style.sealName}>
													<p>{item.name}</p>
												</div>

											</div>

										))}
									</div>
								</List>
							</div>
						</div>
						<div className={style.preview}>
							<div className={style.Title}>
								<span>预览</span>
							</div>
							<div className={style.previewImg}>
								<img src={typeof configType === 'function' ? getSealImages(configType(configData)) : ''} />
							</div>
						</div>

					</div>


					<div className={style.msgInput}>
						<div className={'staffMsgDiv' + " " + style.msgDiv}>
							<List>
								{getFieldDecorator('staffName', {
									initialValue: '',
									rules: [
										{
											required: true,
											message: '标题内容必填！',
											// min:1,
											// max:20,
											pattern: staffName.reg,
										},
									],
								})(
									<InputItem clear placeholder="请输入" onChange={this.getInputValue}>
										<span style={{ color: 'red' }}>*</span>印章名称
                  </InputItem>
								)}
								{
									errorStaffName &&
									<div className={styles.errorMsg} style={{}}>
										请输入1~20位汉字，字母或数字，特殊字符只支持中英文括号
              </div>
								}
								{/* {getFieldDecorator('staffSize', {
              initialValue: staffSize||'',
              rules: [
                {
                  required: true,
                  message: ' 印章尺寸(宽/高)必填！'
                },
              ],
            })(
              <Picker
                data={sealConfigData.filter(item => item.check !== -1).size || []}
                // cols={this.state.cols}
                // value={staffSize}
                // onPickerChange={this.onPickerChange}
                // onOk={v => console.log(v)}
              >
                <InputItem clear editable={false} placeholder="请输入" >
                  <span style={{color:'red'}}>*</span>印章尺寸(宽/高)
                </InputItem>
              </Picker>
            )} */}
								<div style={{ paddingRight: '15px' }}>
									<Picker
										disabled={picker.length === 1}
										cols={1}
										data={picker}
										value={[staffSize]}
										onChange={this.changePicker}
									// onPickerChange={this.onPickerChange}
									// onOk={v => console.log(v)}
									>
										<List.Item arrow={picker.length === 1 ? '' : "horizontal"} align="middle">
											<span style={{ color: 'red' }}>*</span>印章尺寸(宽/高)
                </List.Item>
									</Picker>
								</div>
								{getFieldDecorator('name', {
									initialValue: name || '',
									rules: [
										{
											required: true,
											message: '企业名称必填！',
										},
									],
								})(
									<InputItem style={{ color: '#bbb' }} clear placeholder="请输入所在企业名称" editable={false} onChange={this.getInputNameValue}>
										<span style={{ color: 'red' }}>*</span>企业名称
              </InputItem>
								)}
								{
									this.getForm()
								}
								{/*  {getFieldDecorator('code', {*/}
								{/*  initialValue: '',*/}
								{/*  rules: [*/}
								{/*    {*/}
								{/*      required: true,*/}
								{/*      message: '信用编码必填！',*/}
								{/*    },*/}
								{/*  ],*/}
								{/*})(*/}
								{/*  <InputItem clear placeholder="请输入信用编码" onChange={this.getInputCodeValue}>*/}
								{/*    <span style={{color:'red'}}>*</span>信用编码*/}
								{/*  </InputItem>*/}
								{/*)}*/}

							</List>
						</div>
						{/*<div className={style.Button}>*/}
						{/*<Button className={style.ButtonStyle} onClick={this.makeSure}>使用</Button>*/}
						{/*</div>*/}



					</div>
				</div>
				<div className={style.footerContainer}>
					<Button type="primary" shape="round"
						// disabled={!btnDisabled}
						onClick={this.makeSure}>
						使用
          </Button>
				</div>
			</div>

		)
	}
}


export default createForm()(sealDetail);
